package com.iotstudio.embeddedcloudplatform.util.web;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 当前用户会话数据缓存工具类
 * @author BeFondOfTaro
 * Created at 16:20 2018/1/19
 */
@Component
public class SessionCacheUtil {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static SessionCacheUtil sessionCacheUtil;

    @PostConstruct
    public void init(){
        sessionCacheUtil = this;
        sessionCacheUtil.redisTemplate = this.redisTemplate;
    }

    /**
     * 设置缓存
     * @param key 键
     * @param value 值
     */
    public static void setAttribute(String key, Object value){
        sessionCacheUtil.redisTemplate.opsForHash().put(getUserKey(),key,value);
    }

    /**
     * 删除缓存
     * @param keys 键
     */
    public static void removeAttribute(String... keys){
        for (String key : keys){
            sessionCacheUtil.redisTemplate.opsForHash().delete(getUserKey(),key);
        }
    }

    /**
     * 获取缓存值
     * @param key 键
     * @return 缓存值
     */
    public static Object getAttribute(String key){
        return sessionCacheUtil.redisTemplate.opsForHash().get(getUserKey(),key);
    }

    /**
     * 获得当前用户在redis中缓存的key
     * @return 当前用户在redis中缓存的key
     */
    private static String getUserKey(){
        return "user:" + SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
    }
}
